package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.mapper.ArticleMapper;
import com.woniu.mapper.MedicineMapper;
import com.woniu.pojo.Article;
import com.woniu.pojo.Mark;
import com.woniu.mapper.MarkMapper;
import com.woniu.pojo.Medicine;
import com.woniu.pojo.MedicineMark;
import com.woniu.service.IMarkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 收藏表 服务实现类
 * </p>
 *
 * @author 刘岩
 * @since 2022-10-11
 */
@Service
public class MarkServiceImpl extends ServiceImpl<MarkMapper, Mark> implements IMarkService {

    @Autowired(required = false)
    private MarkMapper markMapper;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private MedicineMapper medicineMapper;

    @Override
    public List<Mark> queryMarkByUserId(Long userId) {
        //构建查询对象
        QueryWrapper<Mark> wrapper = new QueryWrapper<>();
        //判断查询条件非空
        if (userId != null) {
            wrapper.like("user_id",userId);
        }
        //执行查询方法
        List<Mark> markList = markMapper.selectList(wrapper);

        //封装返回对象
        return markList;
    }


    /**
     * 保存收藏数据,跟新收藏数量
     * @param mark
     * @return
     */
    @Override
    public int saveMark(Mark mark) {
        //保存收藏数据
        int row = markMapper.insert(mark);

        //跟新收藏数量
        QueryWrapper<Mark> wrapper = new QueryWrapper<>();

        //若数据为新增资讯收藏
        if (mark.getArticleId() != null) {
            Long articleId = mark.getArticleId();
            wrapper.eq("article_id",articleId);
            //查询收藏表中该资讯ID出现次数=收藏数量
            Long aCount = markMapper.selectCount(wrapper);
            //转换Long格式为String
            String count = aCount.toString();
            //跟新资讯表中的收藏数量
            Article article = articleMapper.selectById(articleId);
            article.setCollectNum(count);
            //保存到资讯表
            articleMapper.updateById(article);
        }
        //若数据为新增药品收藏
        if (mark.getMedicineId() != null) {
            Long medicineId = mark.getMedicineId();
            wrapper.eq("medicine_id",medicineId);
            //查询收藏表中该资讯ID出现次数=收藏数量
            Long mCount = markMapper.selectCount(wrapper);
            //跟新药品表中的收藏数量
            Medicine medicine = medicineMapper.selectById(medicineId);
            medicine.setCollectNum(mCount);
            //保存到资讯表
            medicineMapper.updateById(medicine);
        }

        return row;
    }
}
